package com.sunop.panticommon.common.handler;

import cn.dev33.satoken.exception.NotRoleException;
import com.sunop.panticommon.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.UnknownHostException;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("错误: {}", e.getMessage(), e);
        return Result.error(e.getMessage());
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = ex.getBindingResult().getAllErrors().stream()
                .map(error -> {
                    String fieldName = ((FieldError) error).getField();
                    String errorMessage = error.getDefaultMessage();
                    return Map.entry(fieldName, errorMessage);
                })
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        // 将 Map 转换为字符串
        String errorMessage = errors.entrySet().stream()
                .map(entry -> entry.getKey() + ": " + entry.getValue())
                .collect(Collectors.joining("; "));

        return Result.error(errorMessage);
    }
    @ExceptionHandler(UnknownHostException.class)
    public Result<?> handleUnknownHostException(UnknownHostException e) {
        return Result.error("网络错误：(服务可能未启动，请联系管理员)" + e.getMessage());
    }

    // 处理权限不足异常
    @ExceptionHandler(NotRoleException.class)
    @ResponseBody
    public Result<?> handleNotRoleException(NotRoleException e) {
        return Result.error("您没有足够的权限：" + e.getMessage());
    }
}
